import { View, Text, StatusBar, Image, useWindowDimensions, StyleSheet, TextInput, Pressable, Button, Alert, ToastAndroid } from 'react-native'
import React, { useState } from 'react'
import { zhBorderRadiusBase, zhBorderWidth, zhFontSizeLg, zhSpacingColBase, zhSpacingColLg, zhSpacingRowBase, zhSpacingRowLg, zhThemeColor, zhThemeColorInverse } from '../global'
// 引入眼睛资源
import eyeClose from '../assets/img/eye-close.png'
import eysOpen from '../assets/img/eye-open.png'
import { userLogin } from '../service'
import { Link, useRouter } from 'expo-router'
import AsyncStorage from '@react-native-async-storage/async-storage';

export default function Login() {
  // 获取屏幕宽度
  const imageSize = useWindowDimensions().width * 0.6
  // 用于保存手机号码
  const [phone, setPhone] = useState('13501234567')
  // 用于保存密码
  const [pwd, setPwd] = useState('123456')
  // 用于保存密码可见状态
  const [hidePwd,setHidePwd] = useState(true)
  // 用于保存按钮的背景颜色
  const [btnBgColor,setBtnBgColor] = useState(zhThemeColor)
  // 调用用于路由跳转钩子函数
  const router = useRouter()

  // 处理登录操作
  const doLogin = async () => {
    // 判断手机号码是否为空
    if(phone.trim().length === 0) {
      // 弹出警示框
      Alert.alert(
        '错误！',   // 标题      15:19
        '手机号码不能为空',  //内容 
        [         //按钮组
          {text: '确定',onPress: ()=>console.log('点击了确定')},
          // {text: '取消',onPress: ()=>console.log('点击了取消')}
        ]
      )
      // 阻止往后执行
      return
    }
    // 验证手机号码格式是否正确
    if(!/^1[3-9]\d{9}$/.test(phone)) {
      Alert.alert(
        '错误！',
        '手机号码格式错误',
        [
          {text: '确定'}
        ]
      )
      return
    }
    // 验证密码必须在6~32位之间
    if(pwd.length < 6 || pwd.length > 32) {
      Alert.alert(
        '错误!',
        '密码格式错误',
        [
          {text: '确定'}
        ]
      )
      return
    }
    // 发请求
    const data = await userLogin(phone,pwd)
    // console.log(data)
    if(data.code === 2000) { // 登录成功
      // 弹出吐司对话框
      ToastAndroid.show('欢迎回来',ToastAndroid.LONG)
      // console.log(ToastAndroid.LONG)
      // 存储token
      await AsyncStorage.setItem('userToken',data.token)
      // 跳转
      router.replace('/tabs/home')
    } else {  //登录失败
      Alert.alert(
        '登录失败!',
        '服务器返回的错误消息：' + data.msg,
        [{text: '确定'}]
      )
    }
  }

  return (
    <View>
      {/* F1: 顶部状态栏 */}
      <StatusBar backgroundColor={zhThemeColor} barStyle="light-content" />
      {/* F2: LOGO图 */}
      {/* 本地图片 */}
      <Image
       source={require('../assets/img/logo.png')}
       style={[
        {width: imageSize,height: imageSize},
        ss.logo
       ]} 
      />
      {/* F3: 手机号码输入框组 */}
      <View style={ss.inputGroup}>
        <TextInput
          placeholder='请输入手机号码'
          style={ss.input}
          value={phone}
          // 获取用户输入的值，把值设置给phone
          // 双向数据绑定需要使用onChangeText 参数txt用户输入的值
          onChangeText={txt => setPhone(txt)}
        />
        <Image 
          source={require('../assets/img/cellphone.png')}
          style={[ss.inputIcon,ss.left]} 
        />
        {/* Pressable 用于为一些没有点击事件的组件添加点击事件 */}
        {/* onPressIn 开始按下触发
          onLongPress  长期按下，超过500ms触发
          onPressOut  松开触发
          onPress   整个按下过程结束后触发
          onLongPress和onPress不能混用
        */}
        <Pressable 
          style={[ss.inputIcon,ss.right]}
          // onPress={() => console.log(1111)}
          // onPressIn={() => console.log(2222)}
          // onPressOut={() => console.log(3333)}
          // onLongPress={() => console.log(4444)}
          onPress={() => setPhone('')}
        >
          <Image 
            source={require('../assets/img/clear.png')} 
            style={{width: 25, height: 25}}
          />
        </Pressable>
        
      </View>
      {/* F4: 密码输入框组 */}
      <View style={[ss.inputGroup,ss.pwdGroup]}>
        <TextInput
          placeholder='请输入密码'
          style={ss.input} 
          // secureTextEntry 设置为密码框
          secureTextEntry={hidePwd}
          value={pwd}
          onChangeText={txt => setPwd(txt)}
        />
        <Image 
          source={require('../assets/img/lock.png')}
          style={[ss.inputIcon,ss.left]} 
        />
        <Pressable
          style={[ss.inputIcon,ss.right]}
          onPress={() => setHidePwd(!hidePwd)}
        >
          <Image 
            source={hidePwd ? eyeClose : eysOpen} 
            style={{width: 25, height: 25}}
          />
        </Pressable>
      </View>
      {/* F5: 登录按钮 */}
      {/* Button不能设置样式 */}
      {/* <Button title='登录' color='orange' style={{paddingVertical: 20}} /> */}
      <Pressable
        onPressIn={() => setBtnBgColor('#080')}
        onPressOut={() => setBtnBgColor(zhThemeColor)}
        onPress={() => doLogin()}
      >
        <Text 
          style={[ss.btn,{backgroundColor: btnBgColor}]}
        >登录</Text>
      </Pressable>   
      {/* F6: 忘记密码   */}
      <Text 
        onPress={() => router.push('/findPwd')}
        style={ss.findPwd}
      >忘记密码</Text>
      {/* 销毁跳转 */}
      {/* <Text onPress={() => router.replace('/findPwd')}>忘记密码</Text> */}
      {/* 页面跳转 */}
      <Link href="/test">测试1</Link>
      {/* <Link replace href="/mall/list">忘记密码</Link> */}
    </View>
  )
}

// 创建样式对象,当前组件的样式
const ss = StyleSheet.create({
  logo: {
    marginTop: zhSpacingColLg*8,
    // marginHorizontal 不能写auto属性，只能写数值
    marginLeft: 'auto',
    marginRight: 'auto'
  },
  // F3: 输入框组  
  inputGroup: {
    marginHorizontal: zhSpacingRowLg,
    marginTop: zhSpacingColLg * 3,
    // RN只有relative和absolute，默认relative
    // position: 'relative'
  },
  pwdGroup: {
    marginTop: zhSpacingColLg*2,
  },
  input: {
    borderWidth: zhBorderWidth,
    borderColor: zhThemeColor,
    paddingVertical: zhSpacingColBase,
    paddingRight: zhSpacingRowLg * 4,
    paddingLeft: zhSpacingRowLg * 3,
    borderRadius: zhBorderRadiusBase
  },
  inputIcon: {
    width: 30,
    height: 30,
    position: 'absolute',
    top: zhSpacingColBase
  },
  left: {
    left: zhSpacingRowBase
  },
  right: {
    right: zhSpacingRowBase,
    width: 25,
    height: 25
  },
  btn: {
    backgroundColor: zhThemeColor,
    color: zhThemeColorInverse,
    marginHorizontal: zhSpacingRowLg,
    paddingVertical: zhSpacingColLg,
    textAlign: 'center',
    marginTop: zhSpacingColLg*2,
    borderRadius: zhBorderRadiusBase,
    fontSize: zhFontSizeLg
  },
  findPwd: {
    textAlign: 'center',
    color: zhThemeColor,
    marginTop: zhSpacingColLg
  }
})